package com.es.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.es.api.exception.OACSException;
import com.es.api.SystemResult;
import com.es.system.domain.SysUser;
import com.es.system.domain.SysUserSexEnum;
import com.es.system.domain.SysUserStatusEnum;
import com.es.system.entity.SysUserDO;
import com.es.system.mapper.SysUserMapper;
import com.es.system.service.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 系统用户 服务实现类
 * </p>
 *
 * @author everysucceed
 * @since 2021-12-09
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserDO> implements SysUserService {
    @Override
    public SystemResult<List<SysUser>> page(Integer page, Integer limit, SysUser sysUser) {
        Page<SysUserDO> iPage = new Page<>(page, limit);
        iPage = baseMapper.selectPage(iPage, genWrapper(sysUser));
        List<SysUserDO> list = iPage.getRecords();
        if(list!=null && !list.isEmpty()){
            List<SysUser> data = new ArrayList<>();
            list.forEach(e->{
                SysUser v = new SysUser();
                BeanUtils.copyProperties(e, v);
                v.setSexTitle(SysUserSexEnum.getTitleByCode(e.getSex()));
                v.setUserStatus(SysUserStatusEnum.getTitleByCode(e.getUserStatus()));
                data.add(v);
            });
            SystemResult result = SystemResult.success(data);
            result.setCount(iPage.getTotal());
            return result;
        }
        return SystemResult.empty("暂无数据");
    }

    @Override
    public SystemResult<Serializable> save(SysUser sysUser) throws OACSException {
        if(sysUser == null){
            throw new OACSException("系统用户不能为空");
        }
        SysUserDO sysUserDO = new SysUserDO();
        sysUserDO.setCreateTime(LocalDateTime.now());
        sysUserDO.setUpdateTime(LocalDateTime.now());
        BeanUtils.copyProperties(sysUser,sysUserDO);
        baseMapper.insert(sysUserDO);
        return SystemResult.success(sysUserDO.getDataId());
    }


    /**
     * @param sysUser 生成动态sql
     * @return
     */
    private LambdaQueryWrapper<SysUserDO> genWrapper(SysUser sysUser) {
        if(sysUser == null){
            return  null;
        }
       LambdaQueryWrapper<SysUserDO> wrapper =  Wrappers.lambdaQuery(SysUserDO.class);
        if(sysUser.getDataId()!=null){
            wrapper.eq(SysUserDO::getDataId, sysUser.getDataId());
        }
        return wrapper;
    }
}
